<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :form="form"
      :defaults.sync="defaults"
      :page.sync="page"
      :before-open="beforeOpen"
      ref="crud"
      :permission="permissionList"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
    </avue-crud>
  </basic-container>
</template>
<script>
import { getList, getDetail, update, add, remove } from '@/api/equipment-manage/glue-manage.js';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
export default {
  components: {
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'GLUE_PARTNO_MANAGE',
      fileList: [],
      form: {},
      defaults: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        border: true,
        index: false,
        addBtnText: '添加物料编码',
        menu: true,
        selection: true,
        searchMenuPosition: 'right',
        searchMenuSpan: 4,
        searchSpan: 5,
        menuWidth: 200, //弹框内字段宽度属性
        labelWidth: '180',
        dialogClickModal: false,
        addBtnText: '添加物料编码',
        columnBtn: false,
        column: [
          {
            label: '物料编码',
            prop: 'code',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入物料编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '用料工序',
            prop: 'routeCodes',
            cell: true,
            type: 'select',
            multiple: true,
            dicUrl: '/api/mes-product/apaasworkstation/workstation/list',
            props: {
              label: 'name',
              value: 'code'
            }
          },
          {
            label: '保质期天数(天)',
            prop: 'expirationDays',
            formslot: true,
            type: 'number',
            precision: 0,
            controls: false,
            labelTip: '指可使用的时间管控，从胶水生产日期开始计算过期时间；到达保质期后，对应的物料条码将自动报废',
            rules: [
              {
                required: true,
                message: '请输入保质期天数',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '最短解冻时间(时)',
            prop: 'timeMinRise',
            type: 'number',
            precision: 2,
            controls: false,
            labelTip: '解冻开始后，经过设定的时间后，自动视为解冻结束，物料条码可进行领用生产',
            rules: [
              {
                required: true,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  if (value <= 0) {
                    callback(new Error('最短解冻时间需大于0'));
                  } else if (!value || value === '') {
                    callback(new Error('请输入最短解冻时间'));
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: '最长使用时间（时）',
            prop: 'maxUsageTime',
            type: 'number',
            precision: 2,
            minRows: '',
            labelTip: '指从解冻开始，到生产辅料登记的时间间隔，超过最长使用时间，将无法登记生产。',
            rules: [
              {
                required: false,
                trigger: 'blur'
                // validator: (rule, value, callback) => {
                //   if (value <= 0 && value !== undefined && value !== '') {
                //     callback(new Error('最长使用时间需大于0'));
                //   } else {
                //     callback();
                //   }
                // }
              }
            ]
          }
        ]
      },
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息

      data: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.gluePartNoManage_view, false),
        editBtn: this.vaildData(this.permission.gluePartNoManage_edit, false),
        addBtn: this.vaildData(this.permission.gluePartNoManage_add, false),
        delBtn: this.vaildData(this.permission.gluePartnoManage_delete, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    beforeOpen(done, type) {
      if (['edit'].includes(type)) {
        if (this.form.maxUsageTime == null) {
          this.form.maxUsageTime = '';
        }
        if (typeof this.form.routeCodes === 'string') {
          this.form.routeCodes = this.form.routeCodes.split(',');
        }
      }
      console.log(this.form, 9999);
      done();
    },
    rowSave(row, done, loading) {
      row.routeCodes = row.routeCodes.join(',');
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      params.type = 'GLUE';
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    addBtn() {},
    rowUpdate(form, index, done, loading) {
      if (typeof form.routeCodes != 'string') {
        form.routeCodes = form.routeCodes.join(',');
      }
      update(form).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove([row.id]);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    }
  }
};
</script>
